#pragma once
/*
 *	Copyright © 2008 University of Houston
 *	All rights reserved.
 */

#include <pcap.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <vector>
#include "sniffex.h"
#include "session.h"
#include "logger.h"
#include "analyzer.h"
#include "util.h"

using namespace std;




struct pcap_data
{
	bpf_program 	filterProgram;
	char			errbuf[PCAP_ERRBUF_SIZE];
	pcap_t 			*handle;
	bpf_u_int32 	net;
};

void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);

class Listener
{
public:
	Listener(string device, string portnum, string hosts, string filename,
			 int anaID, int algID);
	~Listener();

	/*
	 * Tells pcap to start listening for packets.
	 */
	void run();

	/*
	 * Returns a pointer to the index'th session object.
	 * @param index The index of the session object that is being requested.
	 * The index of a session increases chronologically, based on the time
	 * that the first packet for the session is observed.
	 * @return A pointer to the requested session object.
	 * @notes The session object that is pointed at by the returned pointer
	 * is the internal session object that is used.
	 */
	const session* operator[](int index);

	/*
	 * This is the callback method which is activated when
	 * our listener recieves a packet.
	 * @param args The Listener is passed to the method
	 * @param header Our packet's header (currently unused)
	 * @param packe The packet itself
	 */
	friend void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);

private:
	bool	initializePcap();
	bool 	setFilter(string s);
	string	getDevice();
	pcap_t* openDevice();

	int addSession(session *s);
	int newSession(timedHeader th);
	int closeSession(int sessionID);


	pcap_data		pcapData;		// libpcap data
	string 			dev;			// capture device name
	string 			port;			// port number
	string			logFilename;	// Log filename
	string			hostString;		// List of tcp hosts
	session_list	sessionList;	// List of open connections
	vector<sessionAnalyzer*> analyzerList;	// List of analyzers for sessions
	string 			filter_exp;		// filter expression [3]
	packetLogger	logger; 		// Logger object
	int				sessionCount;	// Keeps track of session numbers
	int				filterID;		// ID of the selected filter
	int				algID;			// ID of the selected algorithm
};
